//
//  MarketsViewController.m
//  HeXun
//
//  Created by ibokan on 15/11/17.
//  Copyright © 2015年 LGC. All rights reserved.
//

#import "MarketsViewController.h"
#import "StockModelView.h"
#import "GetXMLObject.h"
#import "StockModel.h"
#import "StockInfoViewController.h"
#import "MBProgressHUD.h"
#import "SearchTableViewController.h"
#import "StockInfoModelViewController.h"



@interface MarketsViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
{
    //搜索框
    __weak IBOutlet UITextField *_searchTextField;
    
    //表视图
    __weak IBOutlet UITableView *_tableView;
    
    //分段控制器
    __weak IBOutlet UISegmentedControl *_headSegmentedControl;
    
    NSInteger _segmentIndex;
    
    //表视图数据源
    NSMutableArray *_names;
}
@end

@implementation MarketsViewController

#pragma mark - itemDelegate
-(void)navigationItemToTabarControllerItem
{
    self.tabBarController.navigationItem.leftBarButtonItem = self.navigationItem.leftBarButtonItem;
    self.tabBarController.navigationItem.rightBarButtonItem = self.navigationItem.rightBarButtonItem;
    self.tabBarController.navigationItem.titleView = self.navigationItem.titleView;
    self.tabBarController.navigationItem.title = self.navigationItem.title;
    self.navigationController.navigationBarHidden = NO;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    //初始化表视图数据源
    _names = [NSMutableArray new];
    _segmentIndex = 0;
    //初始化模型
    self.stockModelView = [StockModelView new];
    self.stockModelView.tag = 1;
    self.stockModelView.frame = CGRectMake(0, 152, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
    //把模型视图添加到父视图上
    [self.view addSubview:self.stockModelView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(action:) name:@"transfrom" object:nil];
    //设置表视图的代理
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    //设置搜索单行文本框代理
    _searchTextField.delegate = self;
    _searchTextField.keyboardType = UIKeyboardTypeNumberPad;
    
    //添加键盘附件栏
    UIButton *returnButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 0, 60)];
    [returnButton setTitle:@"返     回" forState:UIControlStateNormal];
    [returnButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    returnButton.titleLabel.font = [UIFont systemFontOfSize:25];
    returnButton.backgroundColor = [UIColor lightGrayColor];
    [returnButton addTarget:self action:@selector(returnButtonTouch) forControlEvents:UIControlEventTouchUpInside];
    
    _searchTextField.inputAccessoryView = returnButton;
    
    
    //设置分段控制器
    //选中时的字体设置
    NSDictionary *selected = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20], NSForegroundColorAttributeName:[UIColor redColor]};
    [_headSegmentedControl setTitleTextAttributes:selected forState:UIControlStateSelected];
    
    //未选中时的字体设置
    NSDictionary *unselected = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:14], NSForegroundColorAttributeName:[UIColor blackColor]};
    [_headSegmentedControl setTitleTextAttributes:unselected forState:UIControlStateNormal];
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //这是通过代码块自定义操作的operation的子类
    NSBlockOperation* cOperation = [NSBlockOperation blockOperationWithBlock:^{
        GetXMLObject* getXMLObject = [GetXMLObject new];
        
        
        NSArray* array = [getXMLObject getStockArrayFromIDArray:@[[NSString stringWithFormat:@"2318"],[NSString stringWithFormat:@"2185"],[NSString stringWithFormat:@"2131"],[NSString stringWithFormat:@"2213"]] sort:4 type:0];
        self.stockModelView.stockArray = array;
        
        NSBlockOperation* dOperation = [NSBlockOperation blockOperationWithBlock:^{
            [self.stockModelView.table1 reloadData];
            [self.stockModelView.table2 reloadData];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
       }];
        //涉及更新UI的操作，就要创建包含这些操作的Operation对象，并把它放入主线程队列
        NSOperationQueue* mainQueue = [NSOperationQueue mainQueue];
        //当Operation放入主线程队列中，其操作就是子主线程中执行
        [mainQueue addOperation:dOperation];
    }];
    
    //创建Operation队列,operation只有在队列里才能跑
    NSOperationQueue* takeMoneyQueue = [NSOperationQueue new];
    
    [takeMoneyQueue addOperation:cOperation];

    
    
}


-(void)dealloc
{
   [[NSNotificationCenter defaultCenter]removeObserver:self name:@"transfrom" object:nil];
}

#pragma mark - 跳转到stockInfoModelViewController的方法
- (void)action:(NSNotification* )notification
{
    if ([notification.object isKindOfClass:[StockModelView class]])
    {
        StockModelView* stockModelView = notification.object;
        if (stockModelView.tag == 1)
        {
            if (_segmentIndex == 0)
            {
                UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                StockInfoModelViewController* stockInfoModelViewController = [storyboard instantiateViewControllerWithIdentifier:@"stockInfoViewModel"];
                NSLog(@"%d",[self.stockModelView.table2 indexPathForSelectedRow].row);
                
                stockInfoModelViewController.pointArr = self.stockModelView.stockArray[[self.stockModelView.table2 indexPathForSelectedRow].row ];
                NSLog(@"%@",self.stockModelView.stockArray[[self.stockModelView.table2 indexPathForSelectedRow].row ]);
                [self.navigationController pushViewController:stockInfoModelViewController animated:YES];
            }
        }
    }
}


#pragma mark - 分段控制器选中段改变触发的方法
- (IBAction)selectedSegmentChanged:(UISegmentedControl *)sender
{
    
    _segmentIndex = sender.selectedSegmentIndex;
    switch (sender.selectedSegmentIndex)
    {
        case 0:
        {
            NSLog(@"大盘");
            
            //把模型视图添加到父视图上
            [self.view addSubview:self.stockModelView];
            
            //清空表视图的数据源，并重新加载一次表视图
            _names = [NSMutableArray new];
            [_tableView reloadData];
            
        }
            break;
            
        case 1:
        {
            NSLog(@"个股");
            
            //移除模型视图
            [self.stockModelView removeFromSuperview];
            
            //填充表视图数据源，并重新加载一次表视图
            _names = [NSMutableArray arrayWithArray:@[@"沪深A股", @"沪市A股", @"深市A股", @"中小板", @"创业板", @"沪市B股", @"深市B股"]];
            [_tableView reloadData];
        }
            break;
            
        case 2:
        {
            NSLog(@"板块");
            
            //移除模型视图
            [self.stockModelView removeFromSuperview];
            
            //填充表视图数据源，并重新加载一次表视图
            _names = [NSMutableArray arrayWithArray:@[@"证监会行业板块",@"权重"]];
            [_tableView reloadData];
        }
            break;
            
        case 3:
        {
            NSLog(@"黄金");
            
            //移除模型视图
            [self.stockModelView removeFromSuperview];
            
            //填充表视图数据源，并重新加载一次表视图
            _names = [NSMutableArray arrayWithArray:@[@"外汇行情"]];
            [_tableView reloadData];
        }
            break;
            
        case 4:
        {
            NSLog(@"基金");
            
            //移除模型视图
            [self.stockModelView removeFromSuperview];
            
            //填充表视图数据源，并重新加载一次表视图
            _names = [NSMutableArray arrayWithArray:@[@"基金净值"]];
            [_tableView reloadData];
        }
            break;
            
        case 5:
        {
            NSLog(@"外汇");
            
            //移除模型视图
            [self.stockModelView removeFromSuperview];
            
            //填充表视图数据源，并重新加载一次表视图
            _names = [NSMutableArray arrayWithArray:@[@"所有汇率"]];
            [_tableView reloadData];
        }
            break;
            
        case 6:
        {
            NSLog(@"港股");
            
            //移除模型视图
            [self.stockModelView removeFromSuperview];
            
            //填充表视图数据源，并重新加载一次表视图
            _names = [NSMutableArray arrayWithArray:@[@"港股指数", @"港股主板", @"创业板", @"红筹股", @"蓝筹股", @"国企股"]];
            [_tableView reloadData];
        }
            break;
            
        case 7:
        {
            NSLog(@"全球");
            
            //移除模型视图
            [self.stockModelView removeFromSuperview];
            
            //填充表视图数据源，并重新加载一次表视图
            _names = [NSMutableArray arrayWithArray:@[@"亚洲股市行情", @"美洲股市行情", @"欧洲股市行情", @"中东股市行情", @"非洲股市行情"]];
            [_tableView reloadData];
        }
            break;
            
        case 8:
        {
            NSLog(@"债券");
            
            //移除模型视图
            [self.stockModelView removeFromSuperview];
            
            //填充表视图数据源，并重新加载一次表视图
            _names = [NSMutableArray arrayWithArray:@[@"国债", @"企业债", @"转债"]];
            [_tableView reloadData];
        }
            break;
            
        default:
            break;
            
    }
}


#pragma mark - 表视图的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _names.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"name" forIndexPath:indexPath];
    
    cell.textLabel.text = _names[indexPath.row];
    
    return cell;
}

#pragma mark - 搜索框回收键盘的方法
-(void)returnButtonTouch
{
    [_searchTextField resignFirstResponder];
}



#pragma mark - 限制搜索框输入的内容不超过6个字符
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //利用传入的参数“预测”文本改变之后的结果
    
    NSString *futureText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    //限制字符串最大长度为6
    if (futureText.length <= 6)
    {
        return YES;
    }
    else
    {
        return NO;
    }
    
}

#pragma mark - 搜索按钮触发的方法
- (IBAction)searchButtonTouch:(UIButton *)sender
{
    SearchTableViewController *searchController = [SearchTableViewController new];
    searchController.searchBarText = _searchTextField.text;
    
    //跳转到搜索结果控制器
    [self.navigationController pushViewController:searchController animated:YES];
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    StockInfoViewController* stockInfoViewController = segue.destinationViewController;
    stockInfoViewController.segmentedControllerIndex = _segmentIndex;
    stockInfoViewController.index = [_tableView indexPathForSelectedRow].row;
}


@end
